package com.warehouse.util;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

/**
 * 高德地图api接口工具类
 * @author 卓汉杰
* */
public class GaudMapUtils {

    // 商家地址经度
    private static  String startLongitude = "110.922597";

    // 商家地址纬度
    private static  String startLatitude = "21.679506";

    // key
    private static  String key = "ab6fcfcd557197a7d08bd5894e1f9e8b";



    /**
     *测量距离
     * @param longitude 用户经度
     * @param latitude 用户纬度
     * @return
     * */
    public static Integer getDistance(String longitude, String latitude) {

        //高德地图url
        String url = "https://restapi.amap.com/v3/distance?key="+key+"&origins="+startLongitude+","+startLatitude+"&destination="+longitude+","+latitude+"&type=2";

        try {
            URL urlObj = new URL(url);
            // 开连接
            URLConnection connection = urlObj.openConnection();
            InputStream is = connection.getInputStream();
            byte[] b = new byte[1024];
            int len;
            StringBuilder sb = new StringBuilder();
            while ((len = is.read(b)) != -1) {
                sb.append(new String(b, 0, len));
            }

            JSONObject resultJOSN = JSONObject.parseObject(sb.toString());
            System.out.println(resultJOSN);
            Object results = resultJOSN.getJSONArray("results").getJSONObject(0).get("distance");


            Integer o = Integer.valueOf(results.toString()) ;
            return o;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static void main(String[] args) {
//        // 地址名称
//        String address = "茂南区官渡街道官渡二路139号";
//
//
//        // 调用自己写好的封装方法
//        JSONObject positionObj = getLngAndLat(address);
//        startLongitude = positionObj.getString("longitude");
//        startLatitude = positionObj.getString("latitude");





        JSONObject positionObj1 = getLngAndLat("茂南区官渡街道官渡二路139号");
        String longitude = positionObj1.getString("longitude");
        String latitude = positionObj1.getString("latitude");
        System.out.println("经度：" + longitude);
        System.out.println("纬度：" + latitude);

        System.out.println("49"+getDistance(longitude, latitude));

//
        System.out.println(getaddress(longitude+","+latitude));


    }

    /**
     * 根据地址查询经纬度
     *
     * @param address
     * @return
     */
    public static JSONObject getLngAndLat(String address) {
        JSONObject positionObj = new JSONObject();

        try {
            // 拼接请求高德的url
            String url = "http://restapi.amap.com/v3/geocode/geo?address=" + address + "&output=JSON&key=" + key;
            // 请求高德接口
            String result = sendHttpGet(url);
            JSONObject resultJOSN = JSONObject.parseObject(result);
            System.out.println("高德接口返回原始数据：");
            System.out.println(resultJOSN);
            JSONArray geocodesArray = resultJOSN.getJSONArray("geocodes");
            if (geocodesArray.size() > 0) {
                String position = geocodesArray.getJSONObject(0).getString("location");
                String[] lngAndLat = position.split(",");
                String longitude = lngAndLat[0];
                String latitude = lngAndLat[1];
                positionObj.put("longitude", longitude);
                positionObj.put("latitude", latitude);
            }
            geocodesArray.getJSONObject(0).getString("location");

        } catch (Exception e) {
            e.printStackTrace();
        }
        return positionObj;
    }

    /**
     * 发送Get请求
     *
     * @param url
     * @return
     */
    public static String sendHttpGet(String url) {
        HttpGet httpGet = new HttpGet(url);
        RequestConfig defaultRequestConfig = RequestConfig.custom()
                .setConnectTimeout(3000)
                .setSocketTimeout(10000)
                .build();
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
        String result = "";
        try {
            CloseableHttpResponse closeableHttpResponse = httpClient.execute(httpGet);
            HttpEntity entity = closeableHttpResponse.getEntity();
            result = EntityUtils.toString(entity, "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 根据经纬度查询地址
     *
     * @param
     * @return
     */
    public static String getaddress(String location) {
            // 拼接请求高德的url
            String url = "http://restapi.amap.com/v3/geocode/regeo?key=" + key + "&location=" + location;
            // 请求高德接口
            String result = sendHttpGet(url);
            JSONObject resultJOSN = JSONObject.parseObject(result);
            System.out.println("高德接口返回原始数据：");
            System.out.println(resultJOSN);
            JSONObject jsonObject = resultJOSN.getJSONObject("regeocode");


        String formatted_address =String.valueOf(jsonObject.get("formatted_address")) ;

        return formatted_address;
    }





}
